package com.jiangxiaofei.citycloud.activity.freshfruits;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.EmptyUtils;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.adapter.GoodListAdapter;
import com.jiangxiaofei.citycloud.adapter.NeedListAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.GoodListBean;
import com.jiangxiaofei.citycloud.bean.NeedBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.FreshConstant;
import com.jiangxiaofei.citycloud.mvp.FreshPersenter;
import com.jiangxiaofei.citycloud.param.SearchParam;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * @author: JiangXFei
 * @date: 2017/11/14 0014
 * @content: 城乡搜索页面
 */

public class FreshFruitsSearchActivity extends BaseActivity
        implements FreshConstant.SearchGoodListView, FreshConstant.SearchNeedListView,
        TextWatcher {
    @InjectView(R.id.img_back)
    ImageView imgBack;
    @InjectView(R.id.tv_search_type)
    TextView tvSearchType;
    @InjectView(R.id.et_search)
    EditText etSearch;
    @InjectView(R.id.img_publish)
    TextView imgPublish;
    @InjectView(R.id.recy_search)
    RecyclerView recySearch;
    @InjectView(R.id.ref_layout)
    SmartRefreshLayout refLayout;
    private PopupWindow mPopupWindowPublish;
    private View popupView;
    private List<GoodListBean> goodListBeans = new ArrayList<>();
    private List<NeedBean> needListBeans = new ArrayList<>();
    private View searchView;
    private PopupWindow popupSearchType;
    private FreshConstant.SearchGoodListPersenter searchGoodPersenter;
    private FreshConstant.SearchNeedListPersenter searchNeedPersenter;
    /**
     * 搜索类类型  1：搜索商品  2：搜索需求
     */
    private int searchType = 1;
    private String key;
    private int page = 1;
    private String lat;
    private String lng;
    private GoodListAdapter goodListAdapter;
    private NeedListAdapter needListAdapter;
    private BDLocation bdLocation;


    @Override
    protected void initView(Bundle savedInstanceState) {
        mActivity = this;
        mContext = this;
        setContentView(R.layout.activity_flea_search_layout);
        ButterKnife.inject(this);
        initPopupPublish();
        initSearchTypePopup();
        initGoodRecyAdapter();
        initRefres();
        etSearch.addTextChangedListener(this);
        searchGoodPersenter = new FreshPersenter(mContext, (FreshConstant.SearchGoodListView) mActivity);
        searchNeedPersenter = new FreshPersenter(mContext, (FreshConstant.SearchNeedListView) mActivity);
        if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
            bdLocation = Constants.bdLocation;
        } else {
            Constants.bdclient.start();
            bdLocation = Constants.bdLocation;
        }
        if (EmptyUtils.isNotEmpty(bdLocation)) {
            lat = String.valueOf(bdLocation.getLatitude());
            lng = String.valueOf(bdLocation.getLongitude());
        }
    }

    /**
     * 初始化商品适配器
     */
    private void initGoodRecyAdapter() {
        goodListAdapter = new GoodListAdapter(R.layout.item_flea_have_goods_layout, goodListBeans);
        goodListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(mContext, FreshFruitsGoodDetailActivity.class);
            intent.putExtra(StringConstants.FRESHGOODID, Integer.valueOf(goodListBeans.get(position).getId()));
            mActivity.startActivity(intent);
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recySearch.setLayoutManager(layoutManager);
        recySearch.setAdapter(goodListAdapter);
    }

    /**
     * 初始化需求适配器
     */
    private void initNeedRecyAdapter() {
        needListAdapter = new NeedListAdapter(R.layout.item_flea_need_layout, needListBeans);
        needListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(mContext, FreshFruitsNeedDetailActivity.class);
            intent.putExtra(StringConstants.FRESHNEEDID, Integer.valueOf(needListBeans.get(position).getId()));
            startActivity(intent);
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recySearch.setLayoutManager(layoutManager);
        recySearch.setAdapter(needListAdapter);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

    }

    @OnClick({R.id.img_back, R.id.img_publish, R.id.tv_search_type})
    public void bOnClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                //返回
                mActivity.finish();
                break;
            case R.id.img_publish:
                //发布
                showPublishPopup();
                break;
            case R.id.tv_search_type:
                //搜索类别选择
                popupSearchType.showAsDropDown(tvSearchType);
                break;
            default:
                break;
        }
    }

    /**
     * 初始化发布popupWindow
     */
    private void initPopupPublish() {
        mPopupWindowPublish = new PopupWindow(mContext);
        popupView = LayoutInflater.from(mContext).inflate(R.layout.popup_ios_buttom, null);
        showAnimation(popupView);
        mPopupWindowPublish.setContentView(popupView);
        mPopupWindowPublish.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindowPublish.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindowPublish.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopupWindowPublish.setFocusable(true);
        mPopupWindowPublish.setOutsideTouchable(false);
        TextView tvGong = popupView.findViewById(R.id.tv_publish_gong);
        TextView tcXu = popupView.findViewById(R.id.tv_publish_xu);
        TextView tvCannel = popupView.findViewById(R.id.tv_cannel);
        tvGong.setOnClickListener(v -> {
            mPopupWindowPublish.dismiss();
            startActivity(new Intent(mContext, FreshFruitsGoodPublishActivity.class));
        });
        tvCannel.setOnClickListener(v -> mPopupWindowPublish.dismiss());
        tcXu.setOnClickListener(v -> {
            mPopupWindowPublish.dismiss();
            startActivity(new Intent(mContext, FreshFruitsNeedPublishActivity.class));
        });
    }

    private void showPublishPopup() {
        showAnimation(popupView);
        mPopupWindowPublish.showAtLocation(getCurrentFocus(), Gravity.BOTTOM, 0, 0); // 设置背景颜色变暗
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.7f;
        mActivity.getWindow().setAttributes(lp);
        mPopupWindowPublish.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp1 = mActivity.getWindow().getAttributes();
            lp1.alpha = 1f;
            mActivity.getWindow().setAttributes(lp1);
        });
    }

    private void showAnimation(View popView) {
        AnimationSet animationSet = new AnimationSet(false);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1.0f);
        alphaAnimation.setDuration(300);
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        translateAnimation.setDuration(300);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(translateAnimation);
        popView.startAnimation(animationSet);
    }

    /**
     * 初始化搜索需求类型选择popupWindow
     */
    private void initSearchTypePopup() {
        popupSearchType = new PopupWindow(mContext);
        searchView = LayoutInflater.from(mContext).inflate(R.layout.popup_good_or_need_select, null);
        TextView tvHave = searchView.findViewById(R.id.tv_have);
        TextView tvNeed = searchView.findViewById(R.id.tv_need);
        tvHave.setOnClickListener(v -> {
            tvSearchType.setText(tvHave.getText().toString());
            initGoodRecyAdapter();
            searchType = 1;
            popupSearchType.dismiss();
        });
        tvNeed.setOnClickListener(v -> {
            tvSearchType.setText(tvNeed.getText().toString());
            initNeedRecyAdapter();
            searchType = 2;
            popupSearchType.dismiss();
        });
        popupSearchType.setContentView(searchView);
        popupSearchType.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupSearchType.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupSearchType.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupSearchType.setFocusable(true);
    }

    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (EmptyUtils.isNotEmpty(s.toString()) && s.toString().length() > 0) {
            switch (searchType) {
                case 1:
                    //搜索供应
                    key = s.toString();
                    goodListBeans.clear();
                    goodListAdapter.notifyDataSetChanged();
                    searchGoodPersenter.searchGoods();
                    break;
                case 2:
                    //搜索需求
                    key = s.toString();
                    needListBeans.clear();
                    needListAdapter.notifyDataSetChanged();
                    searchNeedPersenter.SearchNeeds();
                    break;
                default:
                    break;
            }
        } else {
            goodListBeans.clear();
            goodListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 初始化刷新框架
     */
    private void initRefres() {
        refLayout.setRefreshHeader(new MaterialHeader(this).setShowBezierWave(true));
        refLayout.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        refLayout.setOnLoadmoreListener(refLayout -> {
            refLayout.finishLoadmore(2000);
            page++;
            switch (searchType) {
                case 1:
                    searchGoodPersenter.searchGoods();
                    break;
                case 2:
                    searchNeedPersenter.SearchNeeds();
                    break;
                default:
                    break;
            }
        });
        refLayout.setOnRefreshListener(refreshlayout -> {
            refreshlayout.finishRefresh(2000);
            page = 1;
            switch (searchType) {
                case 1:
                    goodListBeans.clear();
                    goodListAdapter.notifyDataSetChanged();
                    searchGoodPersenter.searchGoods();
                    break;
                case 2:
                    needListBeans.clear();
                    needListAdapter.notifyDataSetChanged();
                    searchNeedPersenter.SearchNeeds();
                    break;
                default:
                    break;
            }
        });
    }

    @Override
    public SearchParam getSearchParam() {
        return new SearchParam(page, key, lat, lng);
    }

    @Override
    public void searchGoodsSuccess(List<GoodListBean> goodListBeans) {
        this.goodListBeans.clear();
        this.goodListBeans.addAll(goodListBeans);
        goodListAdapter.notifyDataSetChanged();
    }

    @Override
    public SearchParam getSearchNeedsParam() {
        return new SearchParam(page, key, lat, lng);
    }

    @Override
    public void searchNeedsSuccess(List<NeedBean> needBeanList) {
        this.needListBeans.clear();
        this.needListBeans.addAll(needBeanList);
        needListAdapter.notifyDataSetChanged();
    }
}
